package com.zjw.touchscreen.server.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtil {

    //私钥
    @Value(value = "${jwt.secret}")
    private String secret;
    @Value(value = "${jwt.expiresAt}")
    private String expiresAt;

    /**
     * 生成签名，expiresAt毫秒后过期
     * @param claimMap
     * @return
     */
    public String createToken(Map<String, String> claimMap) {
        // 设置过期时间
        Date date = new Date(System.currentTimeMillis() + expiresAt);
        // 私钥和加密算法
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 设置头部信息
        Map<String, Object> header = new HashMap<>(2);
        header.put("Type", "Jwt");
        header.put("alg", "HS256");
        // 返回token字符串
        JWTCreator.Builder builder = JWT.create();
        builder.withHeader(header);
        claimMap.forEach(builder::withClaim);
        builder.withExpiresAt(date);
        return builder.sign(algorithm);
    }

    /**
     * 检验token是否正确
     *
     * @param **token**
     * @return
     */
    public Map<String, String> verifyToken(String accessToken) {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(accessToken);
        Map<String, Claim> claims = jwt.getClaims();
        Map<String, String> resultMap = new HashMap<>(claims.size());
        claims.forEach((k, v) -> {
            resultMap.put(k, v.asString());
        });
        return resultMap;
    }

}
